package com.csx.governance.traffic.adapter.outbound;

import com.csx.governance.traffic.adapter.outbound.resttemplate.TrafficLoadBalancerInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;

/**
 * <p> 负载均衡器拦截器的后置处理器 - Spring Cloud LoadBalancer的实现 </p>
 * <p> 主要负责将原生的 {@link LoadBalancerInterceptor} 替换为自定义的 {@link TrafficLoadBalancerInterceptor}</p>
 * @author cuisongxu
 * @date 2023/4/2 12:05
 */
public class LoadBalancerInterceptorBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof LoadBalancerInterceptor) {
            LoadBalancerClient loadBalancerClient = applicationContext.getBean(LoadBalancerClient.class);
            LoadBalancerRequestFactory loadBalancerRequestFactory = applicationContext.getBean(LoadBalancerRequestFactory.class);
            return new TrafficLoadBalancerInterceptor((GenericApplicationContext) applicationContext, loadBalancerClient, loadBalancerRequestFactory);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
